import http.client, random, re, json, pymysql, time

class AgileoneV4:
    def __init__(self):
        self.host = "localhost"
        self.port = 80
        self.cookie = ""
        pass

    def open_home(self):
        conn = http.client.HTTPConnection(self.host, self.port)
        conn.request("GET", "/agileone/")
        data = conn.getresponse().getheader("Set-Cookie")
        cookie = data.split(";")[0]
        self.cookie += cookie + "; "
        print(self.cookie)

    def test_login(self):
        conn = http.client.HTTPConnection(self.host, self.port)
        param = "username=admin&password=admin&savelogin=true"
        header = {"Content-Type": "application/x-www-form-urlencoded",
                  "Cookie": self.cookie}
        conn.request(method="POST", url="/agileone/index.php/common/login/",
                     body=param, headers=header)
        resp = conn.getresponse()
        content = resp.read().decode()
        if content == "successful":
            print("登录成功.")
        else:
            print("登录失败.")

        # 获取登录的响应中的两条Cookie
        for header in resp.getheaders():
            if header[0] == "Set-Cookie":
                self.cookie += header[1].split(";")[0] + "; "


    def test_add(self):
        sequence = random.randint(10000, 99999)  # 为标题和内容生成一个随机数
        conn = http.client.HTTPConnection(self.host, self.port)
        param = "type=Requirement&importance=Medium&headline=这是需求提案标题-%d" \
                "&content=这是需求提案内容-%d&processresult=" % (sequence, sequence)
        header = {"Content-Type": "application/x-www-form-urlencoded",
                  "Cookie": self.cookie}
        conn.request(method="POST", url="/agileone/index.php/proposal/add",
                     body=param.encode("utf-8"), headers=header)
        content_id = conn.getresponse().read().decode()

        # 利用正则表达式进行响应的简单断言
        if re.match("^\\d{3,}$", content_id):
            print("新增需求提案-正则表达式-成功")
        else:
            print("新增需求提案-正则表达式-失败.")

        # 利用数字校验进行响应的简单断言
        if int(content_id) >= 100:
            print("新增需求提案-数字校验-成功.")
        else:
            print("新增需求提案-数字检验-失败.")

        # 利用查询进行断言
        conn = http.client.HTTPConnection(self.host, self.port)
        param = "currentpage=1&proposalid=%s&creator=&type=&importance=" \
                "&headline=&content=&processresult=" % content_id
        conn.request(method="POST", url="/agileone/index.php/proposal/query",
                     body=param.encode("utf-8"), headers=header)
        content = conn.getresponse().read().decode()
        # print(content)
        # json_list = json.loads(content)
        # for i in range(0, len(json_list)-1):
        #     print(json_list[i])
        #     print(json_list[i]['proposalid'])
        #     print(json_list[i]['headline'])
        json_list = json.loads(content)
        proposalid = json_list[0]['proposalid']
        headline = json_list[0]['headline']
        if proposalid == content_id and headline == "这是需求提案标题-%d" % sequence:
            print("新增需求提案-JSON数据-成功.")
        else:
            print("新增需求提案-JSON数据-失败.")

        # 利用数据库查询进行断言
        sql = "SELECT proposalid,headline FROM proposal WHERE proposalid=%s" \
              % content_id
        conn = pymysql.connect(user='root', passwd='',
                               host='localhost', db='agileone', charset='utf8')
        cursor = conn.cursor()
        cursor.execute(sql)
        proposal = cursor.fetchone()
        if proposal[0] == content_id and proposal[1] == "这是需求提案标题-%d" \
                % sequence:
            print("新增需求提案-数据库查询-成功.")
        else:
            print("新增需求提案-数据库查询-失败.")


if __name__ == '__main__':
    agileone = AgileoneV4()
    agileone.open_home()
    agileone.test_login()
    agileone.test_add()